package com.boc.langxiang.ui.fragment.me;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.boc.langxiang.App;
import com.boc.langxiang.Constant;
import com.boc.langxiang.R;
import com.boc.langxiang.contract.me.OrdersWaitPayFragmentContract;
import com.boc.langxiang.entity.events.OrdersEvent;
import com.boc.langxiang.entity.response.ProductEntity;
import com.boc.langxiang.entity.response.ProductListEntity;
import com.boc.langxiang.presenter.me.OrdersWaitPayFragmentPresenter;
import com.boc.langxiang.ui.activity.me.OrdersDetailActivity;
import com.boc.langxiang.ui.adapter.me.section.OrdersSection;
import com.boc.langxiang.ui.adapter.me.section.OrdersWPSectionAdapter;
import com.boc.langxiang.ui.dialog.OrderMePayDialog;
import com.boc.langxiang.ui.fragment.BaseFragment;
import com.boc.langxiang.util.T;
import com.chad.library.adapter.base.BaseQuickAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by admin on 2016/6/23.
 */
public class OrdersWaitPayFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener
        , OrdersWaitPayFragmentContract.View, BaseQuickAdapter.RequestLoadMoreListener, BaseQuickAdapter.OnRecyclerViewItemClickListener {

    @BindView(R.id.recylerview_me_wait_pay)
    RecyclerView recylerviewMeWaitPay;
    @BindView(R.id.swipeLayout_me_wait_pay)
    SwipeRefreshLayout swipeLayoutMeWaitPay;
    private List<OrdersSection> mList;

    private OrdersWaitPayFragmentPresenter mPresenter;
    private OrdersWPSectionAdapter mAdapter;
    private boolean mIsRefresh;
    private boolean mIsLoadmore;
    private int mPage;

    public static OrdersWaitPayFragment getInstance() {
        OrdersWaitPayFragment meWaitPayFragment = new OrdersWaitPayFragment();
        Bundle args = new Bundle();
        args.putString(Constant.ME_ALL_ORDERS, "待付款");
        meWaitPayFragment.setArguments(args);
        return meWaitPayFragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View inflate = View.inflate(getContext(), R.layout.fragment_me_wait_pay, null);
        ButterKnife.bind(this, inflate);
        EventBus.getDefault().register(this);
        return inflate;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mPresenter = new OrdersWaitPayFragmentPresenter(this);
        swipeLayoutMeWaitPay.setOnRefreshListener(this);
        swipeLayoutMeWaitPay.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW);
        recylerviewMeWaitPay.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recylerviewMeWaitPay.setLayoutManager(linearLayoutManager);
        initAdapter();
        initRequest();
    }

    private void initRequest() {
        mPage = 1;
        mPresenter.toPayOrders(String.valueOf(mPage));
    }

    private void initAdapter() {
        mList = new ArrayList<>();
        mAdapter = new OrdersWPSectionAdapter(mContext, R.layout.item_orders_entity, R.layout.head_orders_waitpay, R.layout.foot_orders_waitpay, mList, this);
        mAdapter.setOnRecyclerViewItemClickListener(this);
        View emptyView = LayoutInflater.from(mContext).inflate(R.layout.view_empty, (ViewGroup) recylerviewMeWaitPay.getParent(), false);
        mAdapter.setEmptyView(emptyView);
        mAdapter.openLoadAnimation();
        mAdapter.isFirstOnly(false);
        mAdapter.setOnLoadMoreListener(this);
        mAdapter.openLoadMore(Constant.PAGE_SIZE, true);
        recylerviewMeWaitPay.setAdapter(mAdapter);
        recylerviewMeWaitPay.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(mIsRefresh){
                    return true;
                }
                return false;
            }
        });

    }

    @Override
    public void onRefresh() {
        if (mIsRefresh) {
            return;
        }
        mIsRefresh = true;
        mAdapter.openLoadMore(Constant.PAGE_SIZE, true);
        mPage = 1;
        mPresenter.toPayOrders(String.valueOf(mPage));
    }


    @Override
    public void setBackgroundAlpht(float value) {
        WindowManager.LayoutParams attributes = getActivity().getWindow().getAttributes();
        attributes.alpha = value;
        getActivity().getWindow().setAttributes(attributes);
    }

    @Override
    public void showPopupWindow(View view, PopupWindow popupWindow) {
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
    }

    @Override
    public void onCancelSureClick(PopupWindow cancelPopupWindow, String id) {
        cancelPopupWindow.dismiss();
        if (mPresenter != null) {
            mPresenter.cancelOrders(id);
        }
    }

    @Override
    public void onCancelGiveUpClick(PopupWindow cancelPopupWindow) {
        cancelPopupWindow.dismiss();
    }


    @Override
    public void getPayOrders(final List<ProductListEntity> list) {
        if (!isAdded()) {
            return;
        }
        if (mIsLoadmore) {
            mIsLoadmore = false;
            if (list == null) {
                mAdapter.openLoadMore(false);
                loadDone();
                return;
            }

        } else {
            mIsRefresh = false;
            swipeLayoutMeWaitPay.setRefreshing(false);
            mList.clear();
            if (list == null) {
                loadDone();
                mAdapter.setNewData(mList);
                mAdapter.openLoadMore(false);
                return;
            }
        }

        List<OrdersSection> ordersSections = dataExecute(list);
        mList.addAll(ordersSections);
        mAdapter.setNewData(mList);

        if (list.size() < Constant.PAGE_SIZE) {
            mAdapter.openLoadMore(false);
            loadDone();
        } else {
            mAdapter.openLoadMore(true);
        }
    }

    private List<OrdersSection> dataExecute(List<ProductListEntity> list) {
        if (list == null) {
            return null;
        }
        List<OrdersSection> list1 = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            ProductListEntity entity = list.get(i);
            list1.add(new OrdersSection(true, false, "header", entity));
            for (int j = 0; j < entity.getProduct().size(); j++) {
                ProductEntity product = entity.getProduct().get(j);
                product.setId(entity.getId());
                product.setTotalPrice(entity.getPrice());
                product.setStatus(entity.getStatus());
                list1.add(new OrdersSection(product));
            }
            list1.add(new OrdersSection(false, true, "foot", entity));
        }
        return list1;
    }


    @Override
    public void startDetailActivity(String id, String totalPrice) {
        Intent intent = new Intent(getActivity(), OrdersDetailActivity.class);
        intent.putExtra(Constant.ME_PRODUCT_ID, id);
        intent.putExtra(Constant.ME_PRODUCT_TYPE, Constant.ME_PRODUCT_TYPE_DEFAULT);
        intent.putExtra(Constant.ME_PRODUCT_TOTALPRICE, totalPrice);
        startActivity(intent);
    }

    @Override
    public void cancelOrdersSuccess() {
        Toast.makeText(App.getInstance(), "订单取消成功", Toast.LENGTH_SHORT).show();
        if (mPresenter != null) {
            initRequest();
        }
    }

    @Override
    public void onPay(ProductListEntity item) {
        OrderMePayDialog orderPayDialog = new OrderMePayDialog(mContext, item, this);
        orderPayDialog.show();
        Window win = orderPayDialog.getWindow();
        win.setWindowAnimations(R.style.me_pop_anim_bottom_style);
        win.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = win.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        win.setAttributes(lp);
    }

    @Override
    public void showLoading() {
        if(getUserVisibleHint()){
            showProgressDialog();
        }
    }

    @Override
    public void hideLoading() {
        hideDialog();
    }

    @Override
    public void onError(String code, String msg) {
        mIsRefresh = false;
        swipeLayoutMeWaitPay.setRefreshing(false);
        mList.clear();
        mAdapter.setNewData(mList);
        mAdapter.openLoadMore(false);
        if(getUserVisibleHint()){
            T.showShort(App.getInstance(), msg);
        }
    }

    @Override
    public void onLoadMoreRequested() {
        recylerviewMeWaitPay.post(new Runnable() {
            @Override
            public void run() {
                if (mIsLoadmore) {
                    return;
                }
                mIsLoadmore = true;
                mPage++;
                mPresenter.toPayOrders(String.valueOf(mPage));
            }
        });
    }

    @Override
    public void onItemClick(View view, int position) {
    }

    private void loadDone() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.view_load_done, (ViewGroup) recylerviewMeWaitPay.getParent(), false);
        mAdapter.addFooterView(view);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void ordersUpdate(OrdersEvent e) {
        initRequest();
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }
}
